//
// ios-sim-locale.m
//
//  Copyright 2011 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import <Foundation/Foundation.h>

int Convert() {
  NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
  NSString *sdkVersion = [args stringForKey:@"sdk"];
  if (!sdkVersion) {
    printf("ios-sim-locale -sdk <version> [-language <en|fr|de...>] "
           "[-locale <en_US|fr_CA...>] [-calendar <gregorian|japanese|buddhist>] "
           "[-dump] [-list] [-home] \n");
    return 1;
  }
  BOOL dump = [[[NSProcessInfo processInfo] arguments] containsObject:@"-dump"];
  NSString *path = nil;
  NSString *home = [args stringForKey:@"home"];
  if (home) {
    path = [home stringByAppendingPathComponent:@"Library/Application Support"];
  } else {

    NSArray *paths
        = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
                                              NSUserDomainMask,
                                              YES);
    if ([paths count] != 1) {
      NSLog(@"Unable to find application support directory");
      return 1;
    }
    path = [paths objectAtIndex:0];
  }
  NSString *component
      = [NSString stringWithFormat:
         @"iPhone Simulator/%@/Library/Preferences/.GlobalPreferences.plist",
         sdkVersion];
  path = [path stringByAppendingPathComponent:component];
  NSMutableDictionary *values
      = [NSMutableDictionary dictionaryWithContentsOfFile:path];
  if (!values) {
    NSLog(@"Unable to open file at %@", path);
    return 1;
  }
  if (dump) {
    printf("Before: %s\n", [[values description] UTF8String]);
  }
  NSMutableArray *languages = [values objectForKey:@"AppleLanguages"];
  if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-list"]) {
    for (NSString *lang in languages) {
      printf("%s\n", [lang UTF8String]);
    }
  }
  NSString *language = [args stringForKey:@"language"];
  if (language) {
    if (![languages containsObject:language]) {
      NSLog(@"%@ is unsupported. Please choose from: %@", language, languages);
      return 1;
    }
    [languages removeObject:language];
    [languages insertObject:language atIndex:0];
  }

  NSString *locale = [args stringForKey:@"locale"];
  NSString *calendar = [args stringForKey:@"calendar"];
  if (locale || calendar) {
    NSString *current = [values objectForKey:@"AppleLocale"];
    NSArray *old = [current componentsSeparatedByString:@"@"];
    if ([old count] > 2) {
      NSLog(@"Unexpected Locale: %@", current);
      return 1;
    }
    NSMutableArray *newArray = [NSMutableArray array];
    if (locale) {
      [newArray addObject:locale];
    } else {
      [newArray addObject:[old objectAtIndex:0]];
    }
    if (calendar) {
      [newArray addObject:[NSString stringWithFormat:@"calendar=%@", calendar]];
    } else if ([old count] > 1) {
      [newArray addObject:[old objectAtIndex:1]];
    }
    NSString *new = [newArray componentsJoinedByString:@"@"];
    [values setObject:new forKey:@"AppleLocale"];
  }
  NSString *errStr = nil;
  NSData *list
      = [NSPropertyListSerialization dataFromPropertyList:values
                                                   format:NSPropertyListBinaryFormat_v1_0
                                         errorDescription:&errStr];
  if (!list) {
    NSLog(@"Error generating list. %@", errStr);
    return 1;
  }
  NSError *error = nil;
  if (![list writeToFile:path options:NSDataWritingAtomic error:&error]) {
    NSLog(@"Unable to write to %@ (%@)", path, error);
    return 1;
  }
  if (dump) {
    printf("After: %s\n", [[values description] UTF8String]);
  }
  return 0;
}

int main (int argc, const char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  int value = Convert();
  [pool drain];
  return value;
}
